package com.lab.webSocket.repository;

import com.lab.webSocket.dto.CheckUserIdReturnDto;
import com.lab.webSocket.dto.UserDto;
import com.lab.webSocket.dto.UserInfoDto;
import org.hibernate.query.NativeQuery;
import org.hibernate.transform.Transformers;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

/**
 * Created by xu_jiaHui on 2017/8/26.
 */
public class UserRepositoryImpl {
    @PersistenceContext
    private EntityManager em;

    public UserDto loginCheck(String userAccount, String userPassword) {
        String sql = "{call login_check(?,?)}";
        Query query = em.createNativeQuery(sql).setParameter(1, userAccount).setParameter(2, userPassword);
        query.unwrap(NativeQuery.class).setResultTransformer(Transformers.aliasToBean(UserDto.class));
        return (UserDto) query.getSingleResult();
    }

    public CheckUserIdReturnDto checkUserId(String userAccount) throws Exception {
        String sql = "SELECT  COUNT(*) AS isExist,userIcon AS IconRGB FROM tb_user WHERE userAccount=?";
        Query query = em.createNativeQuery(sql).setParameter(1, userAccount);
        query.unwrap(NativeQuery.class).setResultTransformer(Transformers.aliasToBean(CheckUserIdReturnDto.class));
        return (CheckUserIdReturnDto) query.getSingleResult();
    }

    public List<UserInfoDto> findFriendsByInfo(String info) throws Exception {
        String sql = "SELECT userAccount, userNickname, userIcon from tb_user where CONCAT(userAccount,userNickname) like '%" + info + "%'";
        Query query = em.createNativeQuery(sql);
        query.unwrap(NativeQuery.class).setResultTransformer(Transformers.aliasToBean(UserInfoDto.class));
        return query.getResultList();
    }
}
